import { getScaleCanvasSize } from '@/lib/gifEdit/common'
import { useEffect, useRef } from 'react'

interface Props {
  width: number
  height: number
  images: string[]
  duration: number
}
export default function GifCanvas({ width, height, images, duration }: Props) {
  const canvasRef = useRef<HTMLCanvasElement>(null)

  useEffect(() => {
    if (!canvasRef.current) return
    if (!images || images.length == 0) return
    const canvas = canvasRef.current
    const ctx = canvas.getContext('2d')
    let isend = false
    let lastTime = 0
    let frameTime = 0
    let frame = 0
    const imageList = images.map((url) => {
      const image = new Image()
      image.src = url
      return image
    })
    const anim = (time: number) => {
      if (isend) return
      let delta = time - lastTime
      lastTime = time
      frameTime += delta
      if (frameTime > duration) {
        const step = Math.floor(frameTime / duration)
        frame += step
        frameTime -= duration * step
        if (frame >= images.length) {
          frame = 0
        }
      }
      ctx.clearRect(0, 0, width, height)
      ctx.drawImage(imageList[frame], 0, 0, width, height)

      requestAnimationFrame(anim)
    }
    requestAnimationFrame(anim)

    return () => {
      isend = true
    }
  }, [images, duration])
  const canvasSize = getScaleCanvasSize(width, height, 500)
  return (
    <canvas
      style={{
        width: canvasSize.width,
        height: canvasSize.height,
      }}
      ref={canvasRef}
      width={width}
      height={height}></canvas>
  )
}
